const appointmentApi = require('../../api/appointment')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 预约列表
    appointmentList: [],
    allAppointments: [], // 用于筛选的完整数据
    
    // 筛选相关
    selectedStatus: '', // 当前选中的状态筛选
    statusOptions: [
      { label: '全部', value: '' },
      { label: '待确认', value: 0 },
      { label: '已确认', value: 1 },
      { label: '已完成', value: 2 },
      { label: '已取消', value: 3 }
    ],
    
    // 详情弹窗
    showDetailModal: false,
    selectedAppointment: null,
    
    // 加载状态
    loading: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadAppointmentList()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 检查登录状态
    const token = wx.getStorageSync('token')
    if (!token) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/auth/login/login'
        })
      }, 1500)
      return
    }
    
    // 刷新数据
    this.loadAppointmentList()
  },

  /**
   * 下拉刷新
   */
  onPullDownRefresh() {
    this.loadAppointmentList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 加载预约列表
   */
  async loadAppointmentList() {
    try {
      this.setData({ loading: true })
      
      const appointments = await appointmentApi.getMyAppointments()
      
      // 处理预约数据
      const processedAppointments = this.processAppointmentData(appointments || [])
      
      this.setData({
        allAppointments: processedAppointments,
        appointmentList: processedAppointments,
        loading: false
      })
      
      // 应用当前筛选
      this.applyStatusFilter()
      
    } catch (error) {
      console.error('加载预约列表失败:', error)
      this.setData({ loading: false })
      wx.showToast({
        title: '加载预约列表失败',
        icon: 'none'
      })
    }
  },

  /**
   * 处理预约数据
   */
  processAppointmentData(appointments) {
    return appointments.map(appointment => {
      // 格式化时间
      appointment.createTime = this.formatDateTime(appointment.createTime)
      appointment.updateTime = this.formatDateTime(appointment.updateTime)
      
      // 判断是否可以取消（预约开始前1小时）
      if (appointment.status === 1) {
        const appointmentDateTime = new Date(`${appointment.appointmentDate} ${appointment.appointmentHour}:00:00`)
        const now = new Date()
        const timeDiff = appointmentDateTime.getTime() - now.getTime()
        appointment.canCancel = timeDiff > 60 * 60 * 1000 // 1小时
      } else {
        appointment.canCancel = false
      }
      
      return appointment
    })
  },

  /**
   * 格式化日期时间
   */
  formatDateTime(dateTimeStr) {
    if (!dateTimeStr) return ''
    
    const date = new Date(dateTimeStr)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const hour = String(date.getHours()).padStart(2, '0')
    const minute = String(date.getMinutes()).padStart(2, '0')
    
    return `${year}-${month}-${day} ${hour}:${minute}`
  },

  /**
   * 按状态筛选
   */
  filterByStatus(e) {
    const status = e.currentTarget.dataset.status
    this.setData({
      selectedStatus: status
    })
    this.applyStatusFilter()
  },

  /**
   * 应用状态筛选
   */
  applyStatusFilter() {
    const { allAppointments, selectedStatus } = this.data
    
    let filteredList = allAppointments
    
    if (selectedStatus !== '') {
      filteredList = allAppointments.filter(item => item.status === selectedStatus)
    }
    
    this.setData({
      appointmentList: filteredList
    })
  },

  /**
   * 查看预约详情
   */
  viewAppointmentDetail(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation()
    
    const appointment = e.currentTarget.dataset.appointment
    this.setData({
      selectedAppointment: appointment,
      showDetailModal: true
    })
  },

  /**
   * 关闭详情弹窗
   */
  closeDetailModal() {
    this.setData({
      showDetailModal: false,
      selectedAppointment: null
    })
  },

  /**
   * 取消预约
   */
  async cancelAppointment(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation()
    
    const appointmentId = e.currentTarget.dataset.id
    const appointment = e.currentTarget.dataset.appointment
    
    const result = await this.showConfirmDialog(
      '确认取消',
      `确定要取消预约"${appointment.packageName}"吗？`,
      '确认取消',
      '我再想想'
    )
    
    if (!result) return
    
    try {
      wx.showLoading({ title: '取消预约中...' })
      
      await appointmentApi.cancelAppointment(appointmentId)
      
      wx.hideLoading()
      wx.showToast({
        title: '预约已取消',
        icon: 'success'
      })
      
      // 刷新列表
      this.loadAppointmentList()
      
    } catch (error) {
      console.error('取消预约失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '取消预约失败',
        icon: 'none'
      })
    }
  },

  /**
   * 在弹窗中取消预约
   */
  async cancelAppointmentInModal() {
    const appointment = this.data.selectedAppointment
    
    const result = await this.showConfirmDialog(
      '确认取消',
      `确定要取消预约"${appointment.packageName}"吗？`,
      '确认取消',
      '我再想想'
    )
    
    if (!result) return
    
    try {
      wx.showLoading({ title: '取消预约中...' })
      
      await appointmentApi.cancelAppointment(appointment.id)
      
      wx.hideLoading()
      wx.showToast({
        title: '预约已取消',
        icon: 'success'
      })
      
      // 关闭弹窗并刷新列表
      this.closeDetailModal()
      this.loadAppointmentList()
      
    } catch (error) {
      console.error('取消预约失败:', error)
      wx.hideLoading()
      wx.showToast({
        title: error.message || '取消预约失败',
        icon: 'none'
      })
    }
  },

  /**
   * 去预约页面
   */
  goToAppointment(e) {
    console.log('点击空状态立即预约按钮')

    try {
      wx.switchTab({
        url: '/pages/appointment/appointment',
        success: function() {
          console.log('从空状态跳转预约页面成功')
        },
        fail: function(err) {
          console.error('从空状态跳转预约页面失败:', err)
          wx.showToast({
            title: '跳转失败: ' + (err.errMsg || '未知错误'),
            icon: 'none',
            duration: 3000
          })
        }
      })
    } catch (error) {
      console.error('空状态立即预约按钮处理异常:', error)
      wx.showToast({
        title: '操作异常',
        icon: 'none'
      })
    }
  },

  /**
   * 从预约列表跳转到预约页面
   */
  goToAppointmentFromList(e) {
    // 阻止事件冒泡
    if (e && e.stopPropagation) {
      e.stopPropagation()
    }

    console.log('点击立即预约按钮，准备跳转')

    try {
      wx.switchTab({
        url: '/pages/appointment/appointment',
        success: function() {
          console.log('跳转预约页面成功')
        },
        fail: function(err) {
          console.error('跳转预约页面失败:', err)
          wx.showToast({
            title: '跳转失败: ' + (err.errMsg || '未知错误'),
            icon: 'none',
            duration: 3000
          })
        }
      })
    } catch (error) {
      console.error('立即预约按钮处理异常:', error)
      wx.showToast({
        title: '操作异常',
        icon: 'none'
      })
    }
  },

  /**
   * 显示确认对话框
   */
  showConfirmDialog(title, content, confirmText = '确定', cancelText = '取消') {
    return new Promise((resolve) => {
      wx.showModal({
        title: title,
        content: content,
        confirmText: confirmText,
        cancelText: cancelText,
        success: (res) => {
          resolve(res.confirm)
        },
        fail: () => {
          resolve(false)
        }
      })
    })
  }
}) 